
// src/components/Console/SerialConsole.tsx
import React, { useRef, useEffect, useState } from 'react';
import { Card, Alert, Spin, Button, Space } from 'antd';
import { ClearOutlined, DownloadOutlined } from '@ant-design/icons';
import { useWebSocket } from '../../hooks/useWebSocket';
import { consoleApi } from '../../api/console';

interface SerialConsoleProps {
  vmName: string;
  connectionId: string;
}

const SerialConsole: React.FC<SerialConsoleProps> = ({ vmName, connectionId }) => {
  const terminalRef = useRef<HTMLDivElement>(null);
  const [wsUrl, setWsUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [output, setOutput] = useState<string>('');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    loadConsoleInfo();
  }, [vmName, connectionId]);

  const loadConsoleInfo = async () => {
    try {
      setLoading(true);
      setError(null);
      const info = await consoleApi.getSerialInfo(vmName, connectionId);
      const url = consoleApi.buildWebSocketURL(
        `/console/serial/${connectionId}/${vmName}`
      );
      setWsUrl(url);
    } catch (err: any) {
      setError(err.message || '无法连接到串行控制台');
    } finally {
      setLoading(false);
    }
  };

  const { readyState, lastMessage, sendMessage } = useWebSocket(wsUrl, {
    onMessage: (event) => {
      setOutput((prev) => prev + event.data);
      // 自动滚动到底部
      if (terminalRef.current) {
        terminalRef.current.scrollTop = terminalRef.current.scrollHeight;
      }
    },
    onError: () => {
      setError('WebSocket 连接错误');
    },
  });

  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && inputRef.current) {
      const input = inputRef.current.value;
      sendMessage(input + '\n');
      inputRef.current.value = '';
    }
  };

  const clearOutput = () => {
    setOutput('');
  };

  const downloadLog = () => {
    const blob = new Blob([output], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${vmName}-console-${new Date().toISOString()}.log`;
    a.click();
    URL.revokeObjectURL(url);
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" tip="连接中..." />
      </div>
    );
  }

  if (error) {
    return (
      <Alert
        message="连接失败"
        description={error}
        type="error"
        showIcon
        action={
          <Button size="small" onClick={loadConsoleInfo}>
            重试
          </Button>
        }
      />
    );
  }

  const connectionStatus = readyState === WebSocket.OPEN ? 'connected' : 'disconnected';

  return (
    <div>
      <Space style={{ marginBottom: '16px' }}>
        <Alert
          message={connectionStatus === 'connected' ? '已连接' : '未连接'}
          type={connectionStatus === 'connected' ? 'success' : 'warning'}
          showIcon
        />
        <Button icon={<ClearOutlined />} onClick={clearOutput}>
          清空
        </Button>
        <Button icon={<DownloadOutlined />} onClick={downloadLog}>
          下载日志
        </Button>
      </Space>

      <div
        ref={terminalRef}
        style={{
          backgroundColor: '#000',
          color: '#0f0',
          fontFamily: 'monospace',
          fontSize: '14px',
          padding: '16px',
          height: '400px',
          overflowY: 'auto',
          whiteSpace: 'pre-wrap',
          wordBreak: 'break-all',
        }}
      >
        {output || '等待输出...'}
      </div>

      <input
        ref={inputRef}
        type="text"
        placeholder="在此输入命令，按回车发送..."
        onKeyPress={handleKeyPress}
        disabled={readyState !== WebSocket.OPEN}
        style={{
          width: '100%',
          marginTop: '16px',
          padding: '8px',
          fontSize: '14px',
          fontFamily: 'monospace',
          backgroundColor: '#1a1a1a',
          color: '#fff',
          border: '1px solid #333',
        }}
      />
    </div>
  );
};

export default SerialConsole;
